package com.esreport.Utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 */
public class GuavaCacheUtil {

    private static Logger log = LoggerFactory.getLogger(GuavaCacheUtil.class);

    private final static LoadingCache<String,Object> cache = CacheBuilder.newBuilder()
            .refreshAfterWrite(2,TimeUnit.HOURS)
            .expireAfterAccess(2,TimeUnit.HOURS)
            .maximumSize(1000)
            .concurrencyLevel(8).build(
                    new CacheLoader<String, Object>() {
                        @Override
                        //当本地缓存没有命中时，执行以下方法获取数据并将数据写进缓存
                        public Object load(String s){
                            return null;
                        }
                    }
            );

    public static Object get(String key){
        try {
            return cache.get(key);
        }catch (Exception e){
            log.info("本地缓存未命中，从其他途径获取数据");
            return null;
        }
    }

    public static void put(String key,Object value){
        cache.put(key,value);
    }
}
